import { extname, resolve } from 'path';
import { config } from '@ai/config';
import fastifyCompress from '@fastify/compress';
import cookieParser from '@fastify/cookie';
import fastifyMultipart from '@fastify/multipart';
import fastifyStatic from '@fastify/static';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { CustomSwaggerModule } from './modules/swagger/swagger.module';

const { ADMIN_URL, CLIENT_URL, SERVER_PORT, SERVER_URL } = config;

async function bootstrap() {
    const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());

    CustomSwaggerModule.setup({ app, prefix: 'api-doc' });

    app.register(fastifyCompress);

    app.register(fastifyStatic, {
        root: resolve(process.cwd(), 'public'),
        prefix: '/assets',
        setHeaders: (res, pathname) => {
            if (['.js', '.css'].includes(extname(pathname))) {
                res.setHeader('Cache-Control', 'public, max-age=31536000');
            }
        },
    });

    app.setGlobalPrefix('/api', { exclude: ['/assets'] });

    app.enableCors({ credentials: true, origin: [ADMIN_URL, CLIENT_URL, '*'] });

    app.register(cookieParser, {});

    app.register(fastifyMultipart, { limits: { files: 10, fileSize: 1024 * 1024 * 10 } });

    await app.listen(Number(SERVER_PORT || 3003), '0.0.0.0', (err) => {
        if (err) throw err;
        console.log(`🚀 ~ server listen at http://${SERVER_URL}`);
    });
}
bootstrap();
